package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
//自定义定时任务，实现订单状态的定时处理
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
//判断是否为 null：这是为了确保集合对象已经被初始化。如果集合为 null，调用其方法（如 isEmpty()）会抛出 NullPointerException。
//判断是否为空：这是为了确保集合中有元素。即使集合对象已经被初始化（不为 null），它仍然可能是空的（没有任何元素）
// 例如初始化一个空的 List<String> list = new ArrayList<>();。
    //处理超时订单
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder(){
        log.info("处理超时订单：{}",new Date());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        //select * from orders where status = 1 and ordertime< 当前时间-15分钟
        List<Orders> ordersList = orderMapper.getByStatusandtime(Orders.PENDING_PAYMENT, time);
        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }


    }

    //处理“派送中”状态的订单
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("处理超时订单：{}", new Date());
// select * from orders where status = 4 and order_time < 当前时间-1小时
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusandtime(Orders.DELIVERY_IN_PROGRESS, time);

        if (ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
